from flask import Flask, jsonify, abort, request, redirect, Request
from flask_cors import CORS
from werkzeug.security import check_password_hash, generate_password_hash
from com import db
from ua_parser import user_agent_parser

# 引入蓝图模块
from com.route.user import user
from com.route.search import searchPic
from com.route.collect import collect as userCollect

from flask_jwt import JWT

# 声明app
app = Flask(__name__, instance_relative_config=None)

app.config.from_pyfile("config.py")

# # 配置数据库
db.init_app(app)

# 进行cors
CORS(app)

# 设定发送者
sender = '1596029711@qq.com'

# 设置app的公共变量，其他模块可以使用应用环境中的此设置
app.__setattr__("sender", sender)
# 搜狗： query start
# 百度：queryWord word pn rn
app.__setattr__("urlList", ['https://pic.sogou.com/pics?st=255&mode=255&reqType=ajax&reqFrom=result&tn=0',
                            'https://image.baidu.com/search/acjson?tn=resultjson_com&logid=11973691270317825492&ipn=rj&ct=201326592result&cl=2&lm=-1&ie=utf-8&oe=utf-8&st=-1&z=&ic=0&copyright=&face=0&istype=2&qc=&nc=1&gsm=3c'])

# 加载所有的路由
app.register_blueprint(user, url_prefix="/user")
app.register_blueprint(searchPic, url_prefix="/search")
app.register_blueprint(userCollect, url_prefix="/collect")


# 设置jwt
def authenticate(username, password):
    if username is None:
        return None
    userInDb = db.get_db_dict().execute("select * from user where username = ?", [username]).fetchone()
    print("这是数据库中的人", userInDb)
    if userInDb is None:
        return None
    if check_password_hash(userInDb['password'], password=password):
        userClass = TransportClass(userInDb)
        return userClass
    else:
        return None


def identify(payload):
    id = payload['identity']
    userInDb = db.get_db_dict().execute("select * from user where id = ?", [id]).fetchone()
    userClass = TransportClass(userInDb)
    return userClass


class TransportClass:
    def __init__(self, dictStr):
        for key in dictStr:
            setattr(self, key, str(dictStr[key]))

    def __repr__(self):
        return "<TransportClass: %s>" % self.__dict__


jwt = JWT(app, authentication_handler=authenticate, identity_handler=identify)

# 定义移动端的系统名称
mobileOs = ['iOS', "Android"]


@app.route('/')
def hello_world():
    myUserAgent = request.headers['user-agent']
    osFamily = user_agent_parser.Parse(myUserAgent)['os']['family']

    if osFamily in mobileOs:
        # return redirect('http://m.lxjhua.top')
        return redirect('http://81.70.80.55:5001')
    else:
        # return redirect('http://p.lxjhua.top')
        return redirect('http://81.70.80.55:5002')


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5555, debug=True)
